package com.tian.job;

import com.tian.entity.RetryMessage;
import com.tian.mapper.RetryMessageMapper;
import com.tian.mq.producer.BaseProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * {@code @description:} 补偿发送消息到MQ
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2025-03-19 22:26
 * {@code @version:} 1.0
 */
@Slf4j
@Component
public class BaseRetryMessageJobService {

    @Resource
    private RetryMessageMapper retryMessageMapper;
    @Resource
    private BaseProducer baseProducer;

    private static final int PAGE_SIZE = 100;

    public void retryMessageToMQ(Integer type, Integer status,String mqExchange, String mqRoutingKey) {
        int count = retryMessageMapper.countRetryMessage(type, status);
        if (count == 0) {
            log.info("UserUsedCouponJob execute count is 0");
            return;
        }
        int pageNum = 1;
        while (pageNum <= count / PAGE_SIZE + 1) {
            int start = (pageNum - 1) * PAGE_SIZE;
            List<RetryMessage> retryMessages = retryMessageMapper.selectRetryMessagePage(type, status, start, PAGE_SIZE);
            for (RetryMessage retryMessage : retryMessages) {
                baseProducer.reSend(retryMessage,mqExchange,mqRoutingKey);
            }
            pageNum++;
        }
        log.info("UserUsedCouponJob execute start");
    }
}
